/*
 * Angular.js Uranus plus
 */

(function (window, angular, undefined) {
    'use strict';
    var uranusPlus = {};
    var toastCount = 0;
    var appvar = {};
    var plusinit = false,	 /*加载是否完成*/
        quitcount = 0,	 /*防止按快退出*/
        animate = "slide-in-right", /*动画*/
        isaddlisten = false,
        dthat = 200;	 /*webview动画时常*/



    /*推送进入的页面*/
    if (window.plus) {
        var t = setInterval(function () {
            var info = plus.push.getClientInfo();
            if (info != null) {
                var cid = info.clientid;
                if (cid != null && cid != "") {
                    localStorage.setItem("clientId", cid);
                    clearInterval(t);
                }
            }

            if (info != null) {
                if (plus.os.name == "iOS") {
                    localStorage.setItem('geTuiAppId', info.appid);
                }
                if (plus.os.name == "Android") {
                    localStorage.setItem('geTuiAppId', '000');
                }
            }

        }, 200);



        plusinit = true;
        if (!isaddlisten) {
            plusinitaddlisten();
            isaddlisten = true;
        }

    } else {
        document.addEventListener('plusready', function () {
            var t = setInterval(function () {
                var info = plus.push.getClientInfo();
                if (info != null) {
                    var cid = info.clientid;
                    if (cid != null && cid != "") {
                        localStorage.setItem("clientId", cid);
                        clearInterval(t);
                    }
                }

                if (info != null) {
                    if (plus.os.name == "iOS") {
                        localStorage.setItem('geTuiAppId', info.appid);
                    }
                    if (plus.os.name == "Android") {
                        localStorage.setItem('geTuiAppId', '000');
                    }
                }

            }, 200);




            // var info = plus.push.getClientInfo();
            // alert(23);
            //  alert(info);
            // if (info != null) {
            //     var t= setTimeout(function(){		
            //         var  cid=info.clientid;
            //         if(cid!=null && cid!="")
            //         {
            //             alert(2);alert(cid);
            //             localStorage.setItem("clientId", cid);
            //             clearTimeout(t);
            //         }
            //     },200);

            //     if (plus.os.name == "iOS") {
            //         localStorage.setItem('geTuiAppId',info.appid);
            //     }
            //     if (plus.os.name == "Android") {
            //         localStorage.setItem('geTuiAppId','000');
            //     }

            // }

            plusinit = true;
            if (!isaddlisten) {
                plusinitaddlisten();
                isaddlisten = true;
            }
        });
    }

    /*循环获取cid*/
    function setCid(info, type) {
        var t = setTimeout(function () {
            if (info != null && type != "") {
                var cid = "";
                if (type == "iOS") {
                    cid = info.token;
                }
                if (type == "Android") {
                    cid = info.clientid;
                }
                if (cid != null && cid != "") {
                    localStorage.setItem("clientId", cid);
                    clearTimeout(t);
                }
            }
        }, 200);
    }

    function plusinitaddlisten() {
        plus.key.addEventListener('backbutton', function () {
            uranusPlus.back();
        });
        var angular_body = angular.element(document.getElementsByTagName("body")[0]);
        if (!angular_body.hasClass("app")) {
            angular_body.addClass("app");
        }
        if (plus.os.name == "Android") {
            var pauseDjs;
            /* 退到后台 */
            document.addEventListener("pause", function () {
                var ms = 180;
                pauseDjs = setInterval(function () {
                    ms--;
                    if (ms < 1) {
                        //3分钟自动退出
                        clearInterval(pauseDjs);
                        uranusPlus.quit(true);
                    }
                }, 1000);
            });
            /* 后台苏醒 */
            document.addEventListener("resume", function () {
                if (pauseDjs) {
                    clearInterval(pauseDjs);
                }
            }, false);
        }
    }

    angular.module('UranusPlus', ['ng']).factory('uranusPlus', ['$window', '$rootScope', function ($window, $rootScope) {
        var curWeb = null,
            lastWeb = null,
            exitArr = ["/main/home", "/main/list", "/main/more", "/main/center", "/login/safepwd"];

        uranusPlus = {
            go: function (url) {
                if (url.startWith("http")) {
                    plus.runtime.openURL(url);
                } else {
                    $rootScope.go(url);
                }
            },
            isApp: false,
            /* APPStorage */
            APPStorage: {
                Get: function (key) {
                    var value = plus.storage.getItem(key);
                    var nowTime = new Date().getTime();
                    if (value != null && !/^\(function\(\){/.test(value)) {
                        value = JSON.parse(value);
                        if (value && typeof value == "object") {
                            if (value && value.storagetime) {
                                var temptime = new Date(value.storagetime).getTime();
                                if (nowTime >= temptime) {
                                    uranusPlus.APPStorage.Del(key);
                                    return null;
                                }
                            }
                            if (value.data || value.data === 0) {
                                return value.data;
                            } else {
                                return value;
                            }
                        } else {
                            return value;
                        }
                    } else {
                        value = null;
                    }
                    return value;
                },
                Set: function (key, value, config) {
                    if (uranusPlus) {
                        if (config && config.isExpires) {
                            var tempvalue = {
                                data: value,
                                storagetime: new Date().getTime() + config.expiresTime
                            };
                            plus.storage.setItem(key, JSON.stringify(tempvalue));
                        } else {
                            plus.storage.setItem(key, JSON.stringify(value));
                        }
                    }
                },
                Del: function (key) {
                    plus.storage.removeItem(key);
                },
                DelUser: function () {
                    uranusPlus.APPStorage.Del("u_uid"); //登录状态 
                    uranusPlus.APPStorage.Del("user"); //登录状态  
                    var keyNames = [];
                    var numKeys = plus.storage.getLength();
                    for (var i = 0; i < numKeys; i++) {
                        keyNames[i] = plus.storage.key(i);
                    }
                    for (var key in keyNames) {
                        // alert(keyNames[key])
                        if (typeof keyNames[key] == "string" && keyNames[key].startWith("user_")) {
                            plus.storage.removeItem(keyNames[key]);
                        }
                    }
                },
                //清除过期的缓存
                ClearExpireStorage: function () {
                    var keyNames = [];
                    var numKeys = plus.storage.getLength();
                    for (var i = 0; i < numKeys; i++) {
                        keyNames[i] = plus.storage.key(i);
                    }
                    for (var key in keyNames) {
                        if (keyNames[key].startWith("time_")) {
                            uranusPlus.APPStorage.Get(keyNames[key]);
                        }
                    }
                },
                DelAll: function () {
                    var keyNames = [];
                    var numKeys = plus.storage.getLength();
                    for (var i = 0; i < numKeys; i++) {
                        keyNames[i] = plus.storage.key(i);
                    }
                    for (var key in keyNames) {
                        if (key != null && key != "lauchFlag") {
                            plus.storage.removeItem(keyNames[key]);
                        }
                    }
                },
                StorageKey: function () {
                    if (arguments.length <= 0) {
                        return null;
                    }
                    var s = "";
                    for (var i = 0; i < arguments.length; i++) {
                        if (!arguments[i]) continue;
                        if (arguments[i] instanceof Array) {
                            s += arguments[i].toString().toLowerCase().join('-');
                            s += '-';
                        } else {
                            s += arguments[i].toString().toLowerCase() + '-';
                        }
                    }
                    if (s.length > 0) {
                        s = s.substr(0, s.length - 1);
                    }
                    return s;
                }
            },
            /*webview操作,几乎用不上。不用*/
            webview: {
                currentWebview: function () {
                    return plus.webview.currentWebview();
                },
                /*关闭webview*/
                close: function (id) {
                    plus.webview.close(id, "auto", dthat);
                },
                get: function (id) {
                    return plus.webview.getWebviewById(id);
                },
                all: function () {
                    return plus.webview.all();
                },
                create: function (url) {
                    return plus.webview.create(url);
                }
            },
            init: function (callback) {
                if (window.plus) {
                    plusinit = true;
                }
                if (plusinit) {
                    uranusPlus.isApp = true;
                    callback();
                }
                else {
                    var plusinitinterval = setInterval(function () {
                        if (plusinit) {
                            uranusPlus.isApp = true;
                            clearInterval(plusinitinterval);
                            callback();
                        }
                    }, 200)
                }
            },
            checkNet: function () {
                var netStatus = uranusPlus.networkinfo.getCurrentType();
                if (netStatus == 0 || netStatus == 1) {
                    return false;
                } else {
                    return true;
                }
            },
            isIos: function () {
                return plus.os.name == "iOS";
            },
            isAndroid: function () {
                return plus.os.name == "Android";
            },
            /*震动*/
            vibrate: function () {
                if (this.isIos()) {
                    if (plus.device.model.indexOf("iPhone") >= 0) {
                        plus.device.vibrate();
                    }
                } else {
                    plus.device.vibrate();
                }
            },
            /*退出APP*/
            quit: function (isTrue) {
                if (isTrue) {
                    plus.runtime.quit();
                } else {
                    var main = plus.android.runtimeMainActivity();
                    main.moveTaskToBack(true);
                }
            },
            /* 拨打电话 */
            calltel: function (tel) {
                plus.device.dial(tel, false);
            },
            messageconfirm: function (message, callBackArray, title, buttons) {
                this.buttons = ["确定", "取消"];
                if (buttons != undefined && buttons != "" && buttons instanceof Array) {
                    this.buttons = buttons;
                }
                this.PromptCallback = function (e) {
                    if (callBackArray instanceof Array && callBackArray.length > 0) {
                        if (e.index > -1) {
                            callBackArray[e.index]();
                        }
                    } else {
                        if (e.index == 1) {
                            callBackArray();
                        }
                    }
                }
                if (plus) {
                    plus.nativeUI.confirm(message, this.PromptCallback, title, this.buttons);
                }
            },
            /*返回上一页*/
            back: function () {
                if (plusinit) {
                    if (layer.isShow) {
                        layer.closeAll();
                        return;
                    }
                    if ($rootScope.loginshow) {
                        $rootScope.hidelogin();
                        return;
                    }
                    var currentweb = plus.webview.currentWebview();
                    var chilsweb = currentweb.children();
                    if (chilsweb.length > 0) {
                        for (var i = 0; i < chilsweb.length; i++) {
                            chilsweb[i].close();
                        }
                    }
                    //在safepwd页面返回的时候正常返回
                    if (exitArr.indexOf($window.location.pathname) > -1 && $window.location.search.indexOf("op=modify") == -1) {
                        quitcount = quitcount + 1;
                        if (quitcount == 2) {
                            this.quit(true);
                        } else if (quitcount == 1) {
                            this.toast("再按一次退出");
                            setTimeout(function () {
                                quitcount = 0;
                            }, 2000);
                        }
                    } else if (typeof this.backhandler == "function") {
                        this.backhandler();
                    } else {
                        $window.history.back();
                    }
                } else {
                    $window.history.back();
                }

            },
            /*弹出框*/
            toast: function (message, option, callBack) {
                if (plusinit) {
                    this.message = '网络不给力，请稍后重试';
                    this.option = { verticalAlign: "center" };
                    if (!!message && message != '') {
                        this.message = message;
                    }
                    if (!!option && option != '') {
                        this.option = option;
                    }
                    if ((this.message == '网络不给力，请稍后重试' || this.message == '请求超时' || this.message == '没有网络连接') && toastCount > 0) {
                        return;
                    } else if (this.message == '网络不给力，请稍后重试' || this.message == '请求超时' || this.message == '没有网络连接') {
                        if (toastCount == 0) {
                            toastCount = 1;
                            setTimeout(function () {
                                toastCount = 0;
                            }, 3000);
                        }
                    }
                    plus.nativeUI.toast(this.message, this.option);
                    if (callBack) {
                        setTimeout(callBack, 200);
                    }
                }
            },
            /*图片压缩*/
            compressImage: function (sourceurl, callback) {
                var tourl = "_doc/compressimg.jpg";
                plus.zip.compressImage({
                    src: sourceurl,
                    dst: tourl,
                    quality: 20,
                    overwrite: true
                }, function (event) {
                    callback(null, tourl);
                }, function (error) {
                    callback(error);
                });
            },
            /*获取拍照的图片*/
            GetPhotoByCamera: function (callback) {
                plus.camera.getCamera().captureImage(function (p) {
                    callback(p);
                });
            },
            /*获取相册的图片*/
            GetPhotoByGallery: function (callback) {
                plus.gallery.pick(function (p) {
                    callback(p);
                });
            },
            /*上传图片*/
            UploadFile: function (url, data, files, callback) {
                //出现等待
                var task = plus.uploader.createUpload(url, { method: "POST" },
                    function (t, status) {  //上传完成
                        if (status == 200) {
                            var data = t.responseText;
                            if (data) {
                                data = JSON.parse(data);
                                callback(data);
                            }
                        }
                        //关闭等待
                        plus.uploader.clear(t.state);
                    });

                for (var i in data) {
                    task.addData(i, data[i]);
                }
                for (var i in files) {
                    task.addFile(files[i].path, { key: files[i].name })
                }
                task.start();
            },
            Share: {
                shares: null,
                // ishref: false,
                ids: [{ id: "weixin", ex: "WXSceneSession", name: "微信好友" }, { id: "weixin", ex: "WXSceneTimeline", name: "朋友圈" }, { id: "qq", name: "QQ" }],
                /**
                 * 发送分享消息
                 * @param {plus.share.ShareService} s
                 */
                shareMessage: function (s, obj, shareurl, title, content, pic, success, fail) {
                    var msg = { content: content, extra: { scene: obj.ex } };
                    msg.href = shareurl;
                    msg.title = title;
                    msg.thumbs = [""];//logo地址
                    if (pic) {
                        msg.thumbs = [pic];
                    }
                    s.send(msg, function () {
                        success();
                    }, function (e) {
                        fail(e);
                    });
                }, shareAction: function (obj, shareurl, title, content, pic, success, faid) {
                    var s = null;
                    if (uranusPlus.Share.shares && (!obj.id || !(s = uranusPlus.Share.shares[obj.id]))) {
                        if (faid) {
                            faid("id is error");
                        }
                        return;
                    }
                    if (s.authenticated) {
                        uranusPlus.Share.shareMessage(s, obj, shareurl, title, content, pic, success, faid);
                    } else {
                        s.authorize(function () {
                            uranusPlus.Share.shareMessage(s, obj, shareurl, title, content, pic, success, faid);
                        }, function (e) {
                            if (faid) {
                                faid(e);
                            }
                        });
                    }
                },
                updateShareSerivces: function (err) {
                    plus.share.getServices(function (s) {
                        uranusPlus.Share.shares = {};
                        for (var i in s) {
                            var t = s[i];
                            uranusPlus.Share.shares[t.id] = t;
                        }
                    }, function (e) {
                        err();
                    });
                },
                cancelAuth: function (err) {
                    try {
                        for (var i in uranusPlus.Share.shares) {
                            var s = uranusPlus.Share.shares[i];
                            if (s.authenticated) {

                            }
                            s.forbid();
                        }
                        // 取消授权后需要更新服务列表
                        uranusPlus.Share.updateShareSerivces();
                    } catch (e) {
                        err();
                    }
                }
            },
            /*设置app全局变量 
                uranusPlus.setAppVariable({ test3: "3", test2: "2" }); //参数必须为json格式
            */
            setAppVariable: function (keyvalue) {
                for (var key in keyvalue) {
                    if (keyvalue.hasOwnProperty(key)) {
                        appvar[key] = keyvalue[key];
                    }
                }
                uranusPlus.APPStorage.Set("appvarible", appvar);
            },
            /*获取app全局变量
                uranusPlus.getAppVariable("test3"); 
            */
            getAppVariable: function (key) {
                appvar = uranusPlus.APPStorage.Get("appvarible") || appvar;
                if (key == "all") {
                    return appvar;
                } else {
                    return appvar[key];
                }
            },
            clearAppVarible: function () {
                appvar = {};
                plus.storage.removeItem("appvarible");
            }
        }
        return uranusPlus;
    }]);
})(window, window.angular);
